<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/5/3
 * Time: 上午9:48
 */

namespace common\service;

use common\helpers\predis\Predis;
use yii\mongodb\Database;
use yii;

class ActivityCategoryService
{
    public function getList()
    {
        $key = self::getListCacheKey();
        $booleanExist = Predis::getInstance()->getClient()->client->exists($key);
        if (!$booleanExist) {
            /** @var Database $database */
            $database = Yii::$app->mongo->getDatabase("web");
            $collection = $database->getCollection('activity_category');
            $categoryList = $collection->find()->toArray();
            Predis::getInstance()->getClient()->client->hmset($key, $categoryList);
        }
        $category = Predis::getInstance()->getClient()->client->get($key);
        return $category;
    }

    public function getCategoryById($id)
    {
        $id = intval($id);
        $key = self::getCategoryByIdCacheKey($id);
        $booleanExist = Predis::getInstance()->getClient()->client->exists($key);
        if (!$booleanExist) {
            /** @var Database $database */
            $database = Yii::$app->mongo->getDatabase("web");
            $collection = $database->getCollection('activity_category');
            $category = $collection->findOne(['id' => $id]);
            Predis::getInstance()->getClient()->client->hmset($key, $category);
        }
        $category = Predis::getInstance()->getClient()->client->get($key);
        return $category;
    }

    public function getCategoryBySymbol($symbol)
    {
        $key = self::getCategoryBySymbolCacheKey($symbol);
        $booleanExist = Predis::getInstance()->getClient()->client->exists($key);
        if (!$booleanExist) {
            /** @var Database $database */
            $database = Yii::$app->mongo->getDatabase("web");
            $collection = $database->getCollection('activity_category');
            $category = $collection->findOne(['symbol' => $symbol]);
            if ($category == null) {
                return null;
            }
            Predis::getInstance()->getClient()->client->hmset($key, $category);
        }
        return Predis::getInstance()->getClient()->client->hGetAll($key);
    }

    public static function getCategoryBySymbolCacheKey($symbol)
    {
        return str_replace('\\', '-', __METHOD__) . '-' . $symbol;
    }

    public static function getListCacheKey()
    {
        return str_replace('\\', '-', __METHOD__);
    }

    public static function getCategoryByIdCacheKey($id)
    {
        return str_replace('\\', '-', __METHOD__) . '-' . $id;
    }
}
